package devices

import (
	"context"

	"gitee.com/zhuhuan12/go-modbus"
	"github.com/gogf/gf/v2/frame/g"
)

// 力夫压力传感模拟

type Pressure struct {
	Product    string // 产品Key
	ModbusAddr int8   // modbus地址
	Pressure   int    // 压力
}

func (p *Pressure) NewDevice(modbusValue int8) Device {
	return &Pressure{
		ModbusAddr: modbusValue,
		Product:    "pressure",
		Pressure:   0,
	}
}

func (p *Pressure) GetProductKey() string {
	return p.Product
}

func (p *Pressure) GetModbusAddr() int8 {
	return p.ModbusAddr
}

func (p *Pressure) HandleData(data []byte) (out []byte, err error) {
	out = []byte{}
	if data[1] == 0x03 { // 读取
		beginAddr := int(data[2])<<8 | int(data[3]) // 起始地址
		readLen := int(data[4])<<8 | int(data[5])   // 读取长度
		out = []byte{byte(p.ModbusAddr), 0x03, byte(readLen * 2)}
		for i := 0; i < readLen; i++ {
			addr := beginAddr + i // 对应的地址
			switch addr {
			case 1:
				out = append(out, byte(p.Pressure>>8), byte(p.Pressure)) // 压力
			}
		}
		g.Log().Debug(context.Background(), "读取压力", p.Pressure)
		p.Pressure++
	}
	intValue := modbus.CRC16(out)
	out = append(out, byte(intValue), byte(intValue>>8))
	return
}
